<template>
  <a-form :form="form" layout="vertical" @submit.prevent="handleSubmit">
    <div class="dsp-form-group">
      <!--姓-->
      <a-form-item>
        <a-input
          :placeholder="$t('pro.loginReg.RegFirst')"
          v-decorator="[
          'firstName',
          {
            rules: [{
                required: true, message: $t('pro.loginReg.RegFirName'), whitespace: true
              }, {
                validator: validateToName
              }]
          }
        ]"
        />
      </a-form-item>
      <!--名-->
      <a-form-item>
        <a-input
          :placeholder="$t('pro.loginReg.Reglast')"
          v-decorator="[
          'lastName',
          {
            rules: [{
                required: true, message: $t('pro.loginReg.ReLastName'), whitespace: true
              }, {
                validator: validateToName
              }]
          }
        ]"
        />
      </a-form-item>
    </div>

    <!--邮箱-->
    <a-form-item>
      <a-auto-complete
        :placeholder="$t('pro.loginReg.loginPla')"
        v-decorator="[
            'email',
            {
              rules: [{
                type: 'email', message: $t('pro.loginReg.loginMessage'),
              }, {
                required: true, message: $t('pro.loginReg.loginWra'),
              }]
            }
          ]"
        @search="handleSearch"
      >
        <template slot="dataSource">
          <a-select-option v-for="email in result" :key="email">{{email}}</a-select-option>
        </template>
      </a-auto-complete>
    </a-form-item>

    <div class="dsp-form-group dsp-form-group-password">
      <!--密码-->
      <a-form-item>
        <a-input
          :placeholder="$t('pro.loginReg.passwordPla')"
          v-decorator="[
                                    'passwordDigest',
                                    {
                                        rules: [{
                                        required: true, message: $t('pro.loginReg.passwordMess'),
                                        }, {
                                        validator: validateToPassword,
                                        }],
                                    }
                                    ]"
          :type="visiblePassword?'text':'password'"
        />
      </a-form-item>
      <!--确认密码-->
      <a-form-item>
        <a-input
          :placeholder="$t('pro.loginReg.cofPas')"
          v-decorator="[
                                    'confirm',
                                    {
                                    rules: [{
                                        required: true, message: $t('pro.loginReg.cofPasMess'),
                                    }, {
                                        validator: compareToFirstPassword,
                                    }],
                                    }
                                ]"
          :type="visiblePassword?'text':'password'"
          @blur="handleConfirmBlur"
        />
      </a-form-item>
    </div>
    <!--国家-->
    <a-form-item>
      <a-select
        mode="tag"
        style="width: 100%"
        :tokenSeparators="[',']"
        :placeholder="$t('pro.loginReg.Country')"
        :showSearch="true"
        v-decorator="[
          'country',
          {
            rules: [{ required: true, message: $t('pro.loginReg.CountryMess'), whitespace: true }]
          }
        ]"
      >
        <a-select-option
          v-for="countriesOption in countriesOptions"
          :key="countriesOption.id"
          :value="countriesOption.commonName"
        >{{ countriesOption.commonName }}</a-select-option>
      </a-select>
    </a-form-item>
    <!--公司-->
    <a-form-item>
      <a-input
        :placeholder="$t('pro.loginReg.CompanyName')"
        v-decorator="['company',{
                        rules: [{max:20, required: true, message: $t('pro.loginReg.CompanyMess'), whitespace: true }]
                    }
        ]"
      />
    </a-form-item>
    <!--地址-->
    <a-form-item>
      <a-input
        :placeholder="$t('pro.loginReg.AddressName')"
        v-decorator="['address',{
                        rules: [{max:100, message: $t('pro.loginReg.AddressMess'), whitespace: true }]
                    }]"
      />
    </a-form-item>
    <!--手机号-->
    <!--{
                rules: [{
                  required: false, message: $t('pro.loginReg.PhoneMess')
                }, {
                  validator: validateToPhoneNumber,
                }],
    }-->
    <a-form-item class="phoneNumber">
      <a-input
        :placeholder="$t('pro.loginReg.PhoneNumber')"
        v-decorator="['phone',{
                                rules: [{
                                    required: true, message: $t('pro.loginReg.PhoneMess')
                                    }, {
                                    validator: validateToPhoneNumber,
                                    }],
                                }]"
        style="width: 100%"
      >
        <a-select
          slot="addonBefore"
          :showSearch="true"
          v-decorator="[
                        'telephoneCode',
                        { initialValue: '86' }
                    ]"
          style="width: 70px"
        >
          <a-select-option
            v-for="telephoneCodeOption in telephoneCodeOptions"
            :key="telephoneCodeOption.ituTTelephoneCode"
            :value="telephoneCodeOption.ituTTelephoneCode"
          >{{ telephoneCodeOption.ituTTelephoneCode }}</a-select-option>
        </a-select>
      </a-input>
    </a-form-item>

    <!--验证手机号 待处理 -->
    <!--<a-form-item>
          <a-row :gutter="8">
            <a-col :span="12">
              <a-input
                :placeholder="$t('pro.loginReg.Captcha')"
                v-decorator="[
                  'captcha',
                  {rules: [{ required: true, message: $t('pro.loginReg.CaptchaMess') }]}
                ]"
              />
            </a-col>
            <a-col :span="12">
              <a-button v-text="$t('pro.loginReg.Getcaptcha')"></a-button>
            </a-col>
          </a-row>
    </a-form-item>-->

    <!--注册按钮-->
    <a-form-item>
      <a-button
        type="primary"
        :loading="loading"
        html-type="submit"
        block
        v-text="$t('pro.loginReg.Register')"
      ></a-button>
    </a-form-item>

    <!--注册条款-->
    <a-form-item style="margin-top: -1rem">
      <!-- , whitespace: true -->
      <a-checkbox
        v-decorator="[
          'agreement',
          {
            rules: [{
                required: true, message: $t('pro.loginReg.agreementMess')
              }, {
                validator: validateAgreement
              }]
          }
        ]"
      >
        {{$t('pro.loginReg.read')}}
        <a @click="termsOfUse" v-text="$t('pro.loginReg.agreement')"></a>
      </a-checkbox>
    </a-form-item>
    <look-html :title="$t('pro.public.footer.Terms')" :config="configTO"></look-html>
  </a-form>
</template>

<script>
import lookHtml from "../../components/common/custom/LookHtml";

import { handlelangs } from "@/utils/tool";
import { registered } from "@/api/login";
import { getTermsOfUse } from "@/api/pulldown-data";
import { vPassword, vUserName, vPhone } from "../../utils/validate";
import { handleSearch } from "../../utils/tool";

export default {
  name: "register",
  components: {
    lookHtml
  },
  mounted() {
    this.$store.dispatch("GetCountries").then(res => {
      this.countriesOptions = res;
    });
    this.$store.dispatch("getTelephoneCodeOptions").then(res => {
      this.telephoneCodeOptions = res;
    });
  },
  data() {
    return {
      form: this.$form.createForm(this),
      loading: false,
      countriesOptions: [],
      telephoneCodeOptions: [],
      confirmDirty: false,
      autoCompleteResult: [],
      visiblePassword: false,
      EmailRegistered: false,

      configTO: {
        isOpen: false,
        htmlCode: ""
      },
      result: []
    };
  },
  methods: {
    handleSearch(value) {
      handleSearch(value, this, "result");
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          this.loading = true;
          values.language = handlelangs();
          registered(JSON.stringify(values))
            .then(res => {
              this.loading = false;
              if (res.data.code == 200 && res.data.data) {
                this.$message
                  .success(this.$t("pro.loginReg.successReg"))
                  .then(() => {
                    this.$emit("updatePwd", false);
                    this.$router.push("/login");
                  });
              }
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },

    handleConfirmBlur(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value;
    },

    compareToFirstPassword(rule, value, callback) {
      const form = this.form;
      if (
        value &&
        form.getFieldValue("confirm") !== form.getFieldValue("passwordDigest")
      ) {
        callback(this.$t("pro.loginReg.cofPasWar"));
      } else {
        callback();
      }
    },

    validateToPassword(rule, value, callback) {
      const form = this.form;
      if (
        form.getFieldValue("confirm") !== form.getFieldValue("passwordDigest")
      )
        form.setFieldsValue({ confirm: "" });
      if (value) {
        if (vPassword(value)) {
          callback();
        } else {
          callback(this.$t("pro.loginReg.passwordWra"));
        }
      } else {
        // 账号或密码为空执行回调, 参数为空字符串,
        // 以显示对应模板中input required msg
        callback("");
      }
    },

    validateToName(rule, value, callback) {
      if (value) {
        if (vUserName(value)) {
          callback();
        } else {
          callback(this.$t("pro.loginReg.RegValidate"));
        }
      } else {
        callback("");
      }
    },
    validateAgreement(rule, value, callback) {
      if (value == null || value !== true) {
        callback(this.$t("pro.loginReg.agreementMess"));
      } else {
        callback();
      }
    },

    validateToPhoneNumber(rule, value, callback) {
      if (value) {
        if (vPhone(value)) {
          callback();
        } else {
          callback(this.$t("pro.loginReg.PhoneVali"));
        }
      } else {
        callback("");
      }
    },

    termsOfUse(e) {
      e.preventDefault();
      if (this.$store.getters.getServeTF || !this.configTO.htmlCode) {
        getTermsOfUse().then(res => {
          let { code, data } = res.data;
          if (code == "200") {
            this.$store.dispatch("editTermsOfUse", false);
            this.configTO.htmlCode = data;
            this.configTO.isOpen = true;
          }
        });
      } else {
        this.configTO.isOpen = true;
      }
    }
  }
};
</script>

<style lang="less" scoped>
form {
  padding-top: 3.5px;
}

#app.dark .ant-checkbox-wrapper,
.anticon,
.ant-select {
  color: rgba(0, 0, 0, 0.65) !important;
}

#app.dark .wrapper .ant-input {
  background-color: #fff !important;
}
</style>
<style>
#app.dark .account .form .anticon {
  color: #888 !important;
}

#app.dark .account .form .ant-select-selection-selected-value {
  color: #888 !important;
}
</style>
